// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 

package com.anda.driver.util;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.anda.driver.locator.LocationInfo;

// Referenced classes of package com.anda.driver.util:
//			Constant

public final class DBHelper extends SQLiteOpenHelper
{
	public static final String _TAG = DBHelper.class.getName();
	public static final String DB_NAME = "dri_loc";
	public static final String LOC_COLS[];
	public static final String LOC_TAB = "loc_his";
	public static final int VERSION = 3;
	private static final int DELETE_DAYS = 30;

	public DBHelper(Context context)
	{
		this(context, DB_NAME, null, VERSION);
	}

	public DBHelper(Context context, String s, android.database.sqlite.SQLiteDatabase.CursorFactory cursorfactory, int version)
	{
		super(context, s, cursorfactory, version);
	}

	public synchronized static long insertLoc(Context context, LocationInfo location)
	{
		long id = -1;
		long lastTime = getLastGpsTime(context,null);
		if (Calendar.getInstance().getTimeInMillis() - lastTime < Constant.cellMinTime) return id;
		
		if (location != null)
		{
			ContentValues contentvalues = new ContentValues();
			Integer nullInt = null;
			contentvalues.put("id", nullInt);
			contentvalues.put("type", location.getType());
			contentvalues.put("lat", Double.valueOf(location.getLat()));
			contentvalues.put("lng", Double.valueOf(location.getLng()));
			contentvalues.put("gettime", Long.valueOf(location.getGetTime()));
			contentvalues.put("issent", Integer.valueOf(0));
			contentvalues.put("accuracy", Float.valueOf(location.getAccuracy()));
			contentvalues.put("accessToken",location.getAccessToken());
			contentvalues.put("city", location.getCity());
			contentvalues.put("country", location.getCountry());
			contentvalues.put("countryCode", location.getCountryCode());
			contentvalues.put("region" , location.getRegion());
			contentvalues.put("street" ,location.getStreet());
			contentvalues.put("streetNumber" ,location.getStreetNumber());
			contentvalues.put("subLocality", location.getSubLocality());
			contentvalues.put("featureName", location.getFeatureName());
			contentvalues.put("thoroughfare", location.getThoroughfare());
			contentvalues.put("subAdminArea", location.getSubAdminArea());
			contentvalues.put("addressDetail", location.getAddressDetail());
			contentvalues.put("cityCode", location.getCityCode());
			contentvalues.put("locationDesc", location.getLocationDesc());
			
			SQLiteDatabase sqlitedatabase = (new DBHelper(context)).getWritableDatabase();
			id = sqlitedatabase.insert(LOC_TAB, null, contentvalues);
			int ret = sqlitedatabase.delete(LOC_TAB, "gettime <= ?", new String [] {String.valueOf(getTimeBefore(location.getGetTime(),DELETE_DAYS))});
			Constant.debug("------delete count:-------"+ret);
			sqlitedatabase.close();
			Constant.debug((new StringBuilder()).append("------insertLoc-->").append(id).toString());			
		}
		return id;
	}
	
	public static void updateLocationSendFlag(Context context, int id){
		SQLiteDatabase sqlitedatabase = (new DBHelper(context)).getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("issent", Integer.valueOf(1));
		int ret = sqlitedatabase.update(LOC_TAB, values, "id = ?", new String[]{String.valueOf(id)});
		Constant.debug("-------update "+id+" affect:-------"+ret);
		sqlitedatabase.close();
	}

	private static long getTimeBefore (long time, int days){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		//cal.ad
		cal.add(Calendar.DAY_OF_MONTH, -1 * days);
		return cal.getTimeInMillis();
	}
	
	public static void main() throws ParseException{
//		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Date d = format.parse("2012-07-26 10:30:00");
//		long t = getTimeBefore(d.getTime(), DELETE_DAYS);
//		d.setTime(t);
//		System.out.println(format.format(d));
	}
	
	public static List<LocationInfo> selectAllLoc(Context context)
	{
		ArrayList<LocationInfo> arraylist = new ArrayList<LocationInfo>();
		SQLiteDatabase sqlitedatabase = (new DBHelper(context)).getReadableDatabase();
		Cursor cursor = sqlitedatabase.query(LOC_TAB, LOC_COLS, null, null, null, null, "id desc");
		do
		{
			if (!cursor.moveToNext())
			{
				cursor.close();
				sqlitedatabase.close();
				Constant.debug((new StringBuilder()).append("--------getAllLoc-->").append(arraylist.size()).toString());
				return arraylist;
			}
			arraylist.add( getLocationInfoFromCursor(cursor) );
		} while (true);
	}
	
	public static ArrayList<LocationInfo> getSomeLocList(Context context, String ids){
		Log.d(_TAG,"===============getSomeLocList begin===========");
		StringBuffer selection = new StringBuffer().append(" 1 = 1 ");
		if (ids != null && ids.length() > 1){
			selection.append(" and id not in (").append(ids.substring(0, ids.length() - 1)).append(" ) ");			
		}
		ArrayList<LocationInfo> list = new ArrayList<LocationInfo>();
		SQLiteDatabase sqlitedatabase = (new DBHelper(context)).getReadableDatabase();
		Cursor cursor = sqlitedatabase.query(LOC_TAB, LOC_COLS, selection.toString(), null, null, null, "id desc", " 10 ");
		while (cursor.moveToNext()){
			list.add(getLocationInfoFromCursor(cursor));
		}
		cursor.close();
		sqlitedatabase.close();
		Constant.debug((new StringBuilder()).append("--------getSomeLocList-->").append(list.size()).toString());
		Log.d(_TAG,"===============getSomeLocList end===========");
		return list;
	}
	
	private static LocationInfo getLocationInfoFromCursor(Cursor cursor){
		return new LocationInfo(
				  cursor.getInt(cursor.getColumnIndex(LOC_COLS[0]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[1]))
				, cursor.getDouble(cursor.getColumnIndex(LOC_COLS[2]))
				, cursor.getDouble(cursor.getColumnIndex(LOC_COLS[3]))
				, cursor.getLong(cursor.getColumnIndex(LOC_COLS[4]))
				, cursor.getInt(cursor.getColumnIndex(LOC_COLS[5]))
				, cursor.getFloat(cursor.getColumnIndex(LOC_COLS[6]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[7]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[8]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[9]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[10]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[11]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[12]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[13]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[14]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[15]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[16]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[17]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[18]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[19]))
				, cursor.getString(cursor.getColumnIndex(LOC_COLS[20]))
		);
	}
	
	public static long getLastGpsTime(Context context, String type){
		long lastTime = 0;
		SQLiteDatabase sqlitedatabase = (new DBHelper(context)).getReadableDatabase();
		Cursor cursor ;
		if (type == null){
			cursor = sqlitedatabase.query(LOC_TAB,new String[]{"max(gettime)"},null,null,null,null,null);
		} else {
			cursor = sqlitedatabase.query(LOC_TAB,new String[]{"max(gettime)"},"type=? or type='baidu'",new String[]{type},null,null,null);
		}
		if(cursor.moveToNext()){
			lastTime = cursor.getLong(0);
		}
		cursor.close();
		sqlitedatabase.close();
		Constant.debug((new StringBuilder()).append("--------getLastTime[type=").append(type).append("]-->").append(lastTime).toString());
		return lastTime;
	}

	@Override
	public void onCreate(SQLiteDatabase sqlitedatabase)
	{
		String s = (
				new StringBuilder())
					.append("create table ").append(LOC_TAB)
					.append("(id integer not null primary key")
					.append(",type varchar(4)")
					.append(",lat double")
					.append(",lng double")
					.append(",gettime BIGINT")
					.append(",issent smallint")
					.append(",accuracy float")
					.append(",accessToken varchar(100)")
					.append(",country varchar(100)")
					.append(",countryCode varchar(20)")
					.append(",region varchar(100)")
					.append(",city varchar(100)")
					.append(",street varchar(100)")
					.append(",streetNumber varchar(100)")
					.append(",subLocality varchar(100)")
					.append(",featureName varchar(100)")
					.append(",thoroughfare varchar(100)")
					.append(",subAdminArea varchar(100)")
					.append(",addressDetail varchar(400)")
					.append(",cityCode varchar(20)")
					.append(",locationDesc varchar(100)")
					.append(")")
					.toString();
		sqlitedatabase.execSQL(s);
		Constant.debug((new StringBuilder()).append("---------create database-->").append(s).toString());
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqlitedatabase, int oldVersion, int newVersion)
	{
		String s;
		switch (oldVersion) {
		case 1:
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add subLocality varchar(100) ").toString();
			sqlitedatabase.execSQL(s);
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add featureName varchar(100) ").toString();
			sqlitedatabase.execSQL(s);
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add thoroughfare varchar(100) ").toString();
			sqlitedatabase.execSQL(s);
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add subAdminArea varchar(100) ").toString();
			sqlitedatabase.execSQL(s);
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add addressDetail varchar(400) ").toString();
			sqlitedatabase.execSQL(s);			
			Constant.debug((new StringBuilder()).append("---------upgrade database from ")
					.append(1).append(" to ").append(newVersion).append(" -->").toString());
		case 2:
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add cityCode varchar(20) ").toString();
			sqlitedatabase.execSQL(s);
			s = new StringBuffer().append("alter table ").append(LOC_TAB).append(" add locationDesc varchar(100) ").toString();
			sqlitedatabase.execSQL(s);
			Constant.debug((new StringBuilder()).append("---------upgrade database from ")
					.append(2).append(" to ").append(newVersion).append(" -->").toString());
		case 3:
		}
	}

	static 
	{
		LOC_COLS = new String[]{
				"id", "type", "lat", "lng", "gettime", "issent", "accuracy","accessToken"
				,"country","countryCode","region","city","street","streetNumber","subLocality","featureName"
				,"thoroughfare","subAdminArea","addressDetail","cityCode","locationDesc"
				};
	}
}
